import Vue from 'vue'
import VueRouter from 'vue-router'

import { hasToken} from '@/utils/cookies'
import { MessageBox } from 'element-ui'

Vue.use(VueRouter)

const routes = [
  {
    path: "/",
    redirect: "/login"
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/Login.vue')
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('../views/Register.vue')
  },
  {
    path: '/home',
    name: 'home',
    component: () => import('../views/Home.vue'),

    children: [
      {
        path: "",
        redirect: "index"

      },
      {
        path: "index",
        name: "index",
        component: () => import("@/views/child/Index.vue")
      },
      {
        path: "classes",
        name: "classes",
        component: () => import("@/views/child/Classes.vue")
      },
      {
        path: "students",
        name: "students",
        component: () => import("@/views/child/Students.vue")
      },
      {
        path: "mine",
        name: "mine",
        component: () => import("@/views/child/Mine.vue")
      },
    ]

  },
]

const router = new VueRouter({
  routes
})

// 全局的路由前置守卫---登录权限验证

// 哪些页面不需要登录就能访问 设置白名单
const whitePathList = ["/login", "/register"]

router.beforeEach((to, form, next) => {
  console.log("token",hasToken());
  
  // 判断是否有登录(是否有token值)
  if (hasToken()) {
    // 有登录，直接放行
    whitePathList.includes(to.path)?next("/home/index"):next()
  } else {
    // 未登录，判断去的页面是否包含在白名单内
    if(whitePathList.includes(to.path)){
      // 去的页面包含在白名单，直接放行
       next()
    }else{
      // 去的页面不在白名单 先提示用户登录
      MessageBox.confirm("您未登录，请先登录!","系统提示",{
        icon:"warning",
        confirmButtonText:"确定",
        showCancelButton:false,
      }).then(()=>{
        //点击确定
        next("/login")
      })
    }
  }
})

export default router
